<?php
namespace Macaca\Controller\Admin;

use Macaca;

class Page extends Base {

    public function modulePage() {
        return new Macaca\Module\Admin\Page($this->app);
    }

    public function actionGetList() {
        $app = $this->app;
        $view = new Macaca\View\Admin\Page($app);
        $module = $this->modulePage();
        $linker = $this->linker;

        $data['title'] = 'Macaca 单页管理';
        $data['url_add'] = $linker->toFix('/admin/page/add');
        $data['url_edit'] = $linker->to('/admin/page/edit');
        $data['url_delete'] = $linker->to('/admin/page/delete');
        $data['url_browse'] = $linker->to('/admin/page/browse');

        $page = $linker->router->getParameter('page', 0);
        $pageUrlPre = $linker->to('/admin/page/');
        $itemCount = $module->getCount();
        $data['page_box'] =
            $view->view->page()
                ->setUrlPre($pageUrlPre)->setCurrentLayout('first-pre-list-next-last-total')
                ->getByList($page, $itemCount, 10);

        $data['page'] = $module->getPageList($page, 10);
        $this->response->setBody($view->render($data));
    }

    public function actionAddItem() {
        $app = $this->app;
        $view = new Macaca\View\Admin\PageEditor($app);
        $module = $this->modulePage();

        $data['title'] = '添加单页面';
        $data['url_save'] = $this->linker->toFix('/admin/page/save');

        $data['page'] = $module->getEmptyItem();

        $this->response->setBody($view->render($data));
    }

    public function actionGetItem() {
        $app = $this->app;
        $view = new Macaca\View\Admin\PageEditor($app);
        $module = $this->modulePage();

        $data['title'] = '编辑单页面';
        $data['url_save'] = $this->linker->toFix('/admin/page/save');

        $pageId = $app->router()->getParameter('page_id');
        $data['page'] = $module->getItemById($pageId);

        if (empty($data['page'])) {
            echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;你要编辑的页面不存在！';
        }
        else {
            $this->response->setBody($view->render($data));
        }
    }

    public function actionDeleteItem() {
        $module = $this->modulePage();
        $nid = $this->app->router()->getParameter('page_id');

        if ($module->deleteItemById($nid)) {
            echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;成功删除所选页面。';
        }
        else {
            echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;页面删除失败!';
        }
    }

    public function actionBrowseItem() {
        echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;该功能未实现!';

    }

    public function actionSaveItem() {
        $module = $this->modulePage();
        if ($module->saveItem($_POST)) {
            echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;页面保存成功!';
        }
        else {
            echo '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;页面保存失败!';
        }

    }
} 